-- NewTeamBossInfoView

local AvatarFactory = require("app.public.avatar.AvatarFactory")
local NewTeamBossSkillRender = import(".renders.NewTeamBossSkillRender")
local NewBossHeadRender = import(".renders.NewBossHeadRender")
local IconRender = require("app.widget.renders.IconRender")
local Skill = require("app.public.dao.Skill")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

local defautAction = "mapidle"

local bossHeadNum = 4 -- boss头像最打个数

local panelMiddlePosX = 0 -- 头像居中X坐标

local headWidth = 94 -- 头像宽度
local headDistance = 10 -- 头像间距
local scrollViewOriginWidth = 0
local scrollViewOriginHeight = 0

local dragonBonesPanleWidth = 0 -- 龙骨panel宽
local dragonBonesPanleHeight = 0 -- 龙骨panel高

ClassRef.VIEW_ROOT_RES = Res.NewTeamBossInfoUi

-- 将需要操作的UI控件对应到成员
-- 以后改UI控件名字或者层级的时候只需要改此处对应关系即可
function ClassRef:bindUINameToLocalName()
	self._closeBtn = self._ui["Panel/Button_close"]

	self._panelLeft = self._ui["Panel/Panel_left"]
	self._panelLeftBg = self._ui["Panel/Panel_left/Image"]
	self._panelLeftBtn = self._ui["Panel/Panel_left/Button"]
	self._panelLeftTitle = self._ui["Panel/Panel_left/tlt"]
	self._panelLeftText = self._ui["Panel/Panel_left/Text"]

	panelMiddlePosX = self._ui["Panel/Panel_right/Panel_head"]:getContentSize().width/2

	self._headScrollview = self._ui["Panel/Panel_right/Panel_head/ScrollView_head"]
	scrollViewOriginWidth, scrollViewOriginHeight = self._headScrollview:getContentSize2()
	self._arrow_left = self._ui["Panel/Panel_right/Panel_head/arrow_1"]
	self._arrow_right = self._ui["Panel/Panel_right/Panel_head/arrow_2"]

	-- boss 头像
	self._headScrollview.createRender = function( scrollview, idx )
		local items = scrollview:getChildren()
		local render = items[idx]
		if nil == render then
			render = NewBossHeadRender.create()
			render:onBtnClick( function()
				self:_selectedBossIdx( idx )
			end )
			scrollview:addChild( render )
		end
		render:setVisible(true)
		return render
	end
	local function scrollViewEvent_2(sender, eventType)
		if eventType == ccui.ScrollviewEventType.bounceLeft or
			eventType == ccui.ScrollviewEventType.scrollToLeft then
				self._arrow_left:setVisible( false )
				self._arrow_right:setVisible( true )
				return
		elseif eventType == ccui.ScrollviewEventType.bounceRight or
			eventType == ccui.ScrollviewEventType.scrollToRight then
				self._arrow_left:setVisible( true )
				self._arrow_right:setVisible( false )
				return
		end
	end
	self._headScrollview:addEventListener(scrollViewEvent_2)

	-- boss龙骨动画panel
	self._panelRightItem = self._ui["Panel/Panel_right/Panel_item"]
	self._panelRightBossDB = self._ui["Panel/Panel_right/Panel_item/Panel"] -- boss龙骨动画区
	dragonBonesPanleWidth, dragonBonesPanleHeight = self._panelRightBossDB:getContentSize2()
	self._panelRightBossName = self._ui["Panel/Panel_right/Panel_item/name"]
	self._panelRightBossBtn = self._ui["Panel/Panel_right/Panel_item/Button"] -- 切换至技能按钮

	-- boss掉落信息
	self._bossDropList = self._ui["Panel/Panel_right/Panel_item/ListView"]
	self._bossDropList.createRender = function (list, idx)
		local items = list:getItems()
		local render = items[idx]
		if nil == render then
			render = IconRender.create()
			render:setTipEnable( true )
			render:setTipUnShowOrigin( true )
			list:pushBackCustomItem(render)
		end
		render:setVisible(true)
		return render
	end

	-- 技能说明panel
	self._panelRightText = self._ui["Panel/Panel_right/Panel_text"]
	self._panelRightTextBossName = self._ui["Panel/Panel_right/Panel_text/name"]
	self._panelRightTextBossBtn = self._ui["Panel/Panel_right/Panel_text/Button"] -- 切换至龙骨动画

	-- skills
	self._list = self._ui["Panel/Panel_right/Panel_text/ListView"]
	local skillListViewWidth = self._list:getContentSize2()
	self._list.createRender = function (list, idx)
		local items = list:getItems()
		local render = items[idx]
		if nil == render then
			render = NewTeamBossSkillRender.create()

			local renderWidth = render:getContentSize2()
			render:setScale( skillListViewWidth/renderWidth )

			list:pushBackCustomItem(render)
		end
		render:setVisible(true)
		return render
	end
end

function ClassRef:init()
	self._curSelectedIdx = 0 -- 当前选中的boss索引
	self._bossNum = 4 -- 地下城boss个数
	self._bossInfoList = {} -- 地下城boss信息列表
	self._bossDropStrList = {} -- 地下城boss掉落信息
	self._bossSkillInfoList = {} -- 地下城boss技能信息列表

	self:bindUINameToLocalName()

	-- 关闭UI
	self._closeBtn:addClickEventListener(function()
		executeFunc(self._onCloseView)
	end)

	self._panelLeftBtn:addClickEventListener(function()
		-- 不知做何用途
	end)

	-- 切换至技能说明panel
	self._panelRightBossBtn:addClickEventListener(function()
		self._panelRightItem:setVisible( false )
		self._panelRightText:setVisible( true )
	end)

	-- 切换至boss龙骨panel
	self._panelRightTextBossBtn:addClickEventListener(function()
		self._panelRightItem:setVisible( true )
		self._panelRightText:setVisible( false )
	end)
end

function ClassRef:show()
	self:setVisible( true )
	self:openAction( true )
end

function ClassRef:setDungeonName( dungeonsName )
	dungeonsName = dungeonsName or ""
	self._panelLeftTitle:setString( dungeonsName )
end

-- 刷新副本boss信息
function ClassRef:initDungeonsBossInfo( teamTargetId )
	local dunPveInfo = GD:queryDungeonPVEInfoById( teamTargetId )

	-- 初始化左侧信息
	local bgPath = GD:getImagePath(Res.teamtarget_pic, dunPveInfo.dungeonBg)
	if bgPath then
		self._panelLeftBg:loadTexture( bgPath )
	end
	self._panelLeftText:setString( L(dunPveInfo.dungeonDes) )

	-- local finalBossList = dunPveInfo.finalBoss -- 最终boss标记
	local bossInfoList = string.split( dunPveInfo.monsters, ";" ) -- npc_res|class_skill ; npc_res|class_skill
	self._bossNum = #bossInfoList
	for i = 1, self._bossNum do
		local eachBossInfoList = string.split( bossInfoList[i], "|" ) -- npc_res | class_skill
		local bossRes = GD:queryNpcRes( eachBossInfoList[1] )

		-- 刷新boss头像
		local render = self._headScrollview:createRender(i)
		render:setData( bossRes )

		self._bossInfoList[ i ] = bossRes

		if not self._bossSkillInfoList[ i ] then
			self._bossSkillInfoList[ i ] = {}
		end
        local skillList = GD:querySkillsByTeam( eachBossInfoList[2] )
        for i2,v in ipairs( skillList ) do
	        local skillTemp = Skill.new()
	        skillTemp:read( { uid = v.ID } )
	        table.insert( self._bossSkillInfoList[ i ], skillTemp )
        end
	end

	-- 调整boss头像 scrollView 的滚动区
	local innerContainer = self._headScrollview:getInnerContainer()
	local innerContainerWidth = scrollViewOriginWidth
	self._arrow_left:setVisible( false )
	if bossHeadNum < self._bossNum then -- render个数超过一页
		self._arrow_right:setVisible( true )
		self._headScrollview:setTouchEnabled( true )

		innerContainerWidth = headWidth * self._bossNum + ( self._bossNum - 1 ) * headDistance
	else
		self._arrow_right:setVisible( false )
		self._headScrollview:setTouchEnabled( false )
	end
	innerContainer:setContentSize( cc.size( innerContainerWidth, scrollViewOriginHeight ) )

	-- 调整头像render位置
	local allBossHeadRender = self._headScrollview:getChildren()
	if bossHeadNum < self._bossNum then -- render个数超过一页
		for i = 1, self._bossNum do
			allBossHeadRender[i]:setPositionX( ( headWidth + headDistance ) * ( i - 1 ) )
		end
	else
		display.autoAdjustNodesPosX( innerContainerWidth, allBossHeadRender, self._bossNum, headDistance )
	end

	local bossDropList = string.split( dunPveInfo["rewards"..UD:getClass()], ";" ) -- boss掉落信息
	-- assert( #bossDropList == self._bossNum, " ---------->>> 配置的boss掉落信息跟boss个数不等?" )

	self._bossDropStrList = {}
	for i,v in ipairs( bossDropList ) do
		if not self._bossDropStrList[ i ] then
			self._bossDropStrList[ i ] = {}
		end
		local dropList = string.split( v, "&" )
		for i2,v2 in ipairs(dropList) do
			local itemData = UD:parseRewardToBagItem( v2 )
			table.insert( self._bossDropStrList[ i ], itemData )
		end
	end

	self._panelRightItem:setVisible( true )
	self._panelRightText:setVisible( false )

	self._curSelectedIdx = nil
	self:_selectedBossIdx( 1 )
end

-- 选中具体boss
function ClassRef:_selectedBossIdx( bossIdx )
	if self._curSelectedIdx == bossIdx then
		return
	end
	self._curSelectedIdx = bossIdx
	for i,v in ipairs( self._headScrollview:getChildren() ) do
		v:setSelected( i == bossIdx )
	end
	self:_refreshBossInfo( bossIdx )
end

-- 刷新具体选中的单个boss信息
function ClassRef:_refreshBossInfo( idx )
	local bossRes = self._bossInfoList[ idx ]
	AvatarFactory.preloadNpcById( bossRes.ID, function()
		local function createNpc()
			-- boss dragonBones
			local bossArmatrueNode = AvatarFactory.createNpcById(bossRes.ID)
			if bossArmatrueNode then
                local conf = GD:getDungeonBossPreviewConfById(bossRes.ID)
                self._panelRightBossDB:removeAllChildren()
				self._panelRightBossDB:addChild(bossArmatrueNode)
				if bossArmatrueNode:hasAnimation(defautAction) then
					bossArmatrueNode:getAnimation():play(defautAction)
				end

				local box = bossArmatrueNode:getBoundingBox()
				local scale = math.min(dragonBonesPanleWidth/box.width, dragonBonesPanleHeight/box.height)
                if conf and conf.scale then     --策划手动添加的缩放
                    scale = scale * tonumber(conf.scale) / 100
                end
				bossArmatrueNode:setScale(scale)

				local box2 = bossArmatrueNode:getBoundingBox()
				local pos = self._panelRightBossDB:convertToNodeSpace(cc.p(box2.x + box2.width/2, box2.y))

                --策划手动添加的偏移
                local nodePosX
                if conf and conf.Xoffset then
                    nodePosX = dragonBonesPanleWidth/2 - pos.x + tonumber(conf.Xoffset) / 100
                else
                    nodePosX = dragonBonesPanleWidth/2 - pos.x
                end
				bossArmatrueNode:setPositionX(nodePosX)
                if conf and conf.Yoffset then
                    bossArmatrueNode:setPositionY(tonumber(conf.Yoffset) / 100)
                end
			end
		end
		if not tolua.isnull( self ) then
			self:performWithDelay( createNpc, 0.05 )
		end
	end )

	-- boss drop info
	local bossReward = self._bossDropStrList[idx]
	self._bossDropList:stopAllActions()
	local dropLen = #bossReward
	local dropCurIdx = 0
	local function refreshBossDrop()
		dropCurIdx = dropCurIdx + 1
		if dropCurIdx <= dropLen then
			local render = self._bossDropList:createRender( dropCurIdx )
			render:setData( bossReward[ dropCurIdx ] )
		else
			--删掉多余的item
			display.removeListUnuseItem( self._bossDropList, dropLen )
			self._bossDropList:stopAllActions()

			self._bossDropList:forceDoLayout()
			self._bossDropList:refreshView()
		end
	end
	if dropLen > 0 then
		local items = self._bossDropList:getItems()
		for i,item in ipairs(items) do
			item:setVisible(false)
		end
		self._bossDropList:setVisible(true)
		self._bossDropList:schedule( refreshBossDrop, 0)
	else
		self._bossDropList:setVisible(false)
	end

	-- boss Info
	local bossInfo = GD:queryNpc( bossRes.ID )
	self._panelRightBossName:setString( L(bossInfo.name) )
	self._panelRightTextBossName:setString( L(bossInfo.name) )

	-- boss Skill
	local bossSkillList = self._bossSkillInfoList[ idx ]
	self._list:stopAllActions()
	local skillLen = #bossSkillList
	local skillCurIdx = 0
	local function refreshBossSkill()
		skillCurIdx = skillCurIdx + 1
		if skillCurIdx <= skillLen then
			local render = self._list:createRender(skillCurIdx)
			render:setData( bossSkillList[ skillCurIdx ] )
		else
			--删掉多余的item
			display.removeListUnuseItem(self._list, skillLen)
			self._list:stopAllActions()
		end
		self._list:requestRefreshView()
		self._list:forceDoLayout()	
	end
	if skillLen > 0 then
		local items = self._list:getItems()
		for i,item in ipairs(items) do
			item:setVisible(false)
		end
		self._list:setVisible(true)
		self._list:schedule( refreshBossSkill, 0)
	else
		self._list:setVisible(false)
	end
end

return ClassRef
